package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"shop/api/request"
	"shop/initernal/dao"
	"shop/initernal/model"
	"shop/pkg"
)

func Register(c *gin.Context) {
	var req request.Register

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "获取参数失败",
			"data":    err.Error(),
		})
		return
	}
	var data model.User
	dao.GetOneByFields(&model.User{Mobile: req.Mobile}, &data)
	if data.Id > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "用户已存在",
			"data":    nil,
		})
		return
	}
	user := model.User{
		Mobile:   req.Mobile,
		Password: req.Password,
		Email:    req.Email,
	}
	if !dao.Create(&user) {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "新增用户失败",
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "注册成功",
		"data":    user,
	})
}

func Login(c *gin.Context) {
	var req request.Login

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "获取参数失败",
			"data":    err.Error(),
		})
		return
	}

	var user model.User
	if !dao.GetOneByFields(&model.User{Mobile: req.Mobile, Password: req.Password}, &user) {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "用户登录失败",
			"data":    nil,
		})
		return
	}

	token, err := pkg.NewJWT("2212a").CreateToken(pkg.CustomClaims{
		ID: user.Id,
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "token 生成失败",
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "登录成功",
		"data":    token,
	})
}
